package com.tz.dao.impl;

import com.tz.dao.IUserDao;
import com.tz.entity.User;
import com.tz.util.HibernateCallback;
import com.tz.util.HibernateTemplate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.stereotype.Component;

/**
 * Created by heziqian on 2016/10/21.
 */
@Component
public class UserDaoImpl implements IUserDao {

	
	//添加用户
	@Override
	public void insterUser(final User user) {
		HibernateTemplate.execute(new HibernateCallback() {

			@Override
			public Object doInHibernate(Session ses) throws HibernateException {
				ses.save(user);
				return null;
			}
		});
		
	}

	//根据名字查用户?
	@Override
	public User selectUserByName(final String name) {
		
		 return (User) HibernateTemplate.execute(new HibernateCallback() {
			
			@Override
			public Object doInHibernate(Session ses) throws HibernateException {
				
				return ses.createQuery("from com.tz.entity.User u where u.username=?")
						.setParameter(0, name).uniqueResult();
			}
		}) ;
	
	}

	@Override
	public User selectUser(final String username, final String password) {
		return (User) HibernateTemplate.execute(new HibernateCallback() {
			@Override
			public Object doInHibernate(Session ses) throws HibernateException {
				return ses
						.createQuery(
								"from com.tz.entity.User u where u.username=? and u.password=?")
						.setParameter(0, username).setParameter(1, password)
						.uniqueResult();
			}
		});
	}

}
